#!/usr/bin/perl -w
use Net::FTP;
use 5.010;

$CACHE_SIZE = 100;

@add = qw(
	10.20.79.1
	10.20.66.2
	10.20.85.2
);
$login_name = 'anonymous';
$login_passwd = '-anonymous@';

&init();

for (my $i = 0; $i < @add; $i++)
{
	&get_index($add[$i], $OUT_FILE[$i]);
}


#----------------SUB FUNCTIONS
sub get_index
{
	my $add = $_[0];
	my $out_file = $_[1];
	my @dir;
	my @output_cache;
	my $count = 0;
	my $pwd;
	my @sub;
	#
	#establish connections
	#
	$ftp = Net::FTP->new($add , Debug => 0)
		or die "Cannot connect to $_[0]: $@";

	$ftp->login($login_name, $login_passwd)
		or die "Cannot login ", $ftp->message;

	push @dir, "/";
	while (@dir)
	{
		$pwd = pop @dir;
		@sub = $ftp->dir("$pwd");
			#or die "Cannot get directory: $pwd";
		foreach (@sub)
		{
			@para = split;
			my $size = $para[4];
			my $name = $para[8];
			my $isdir = substr("$para[0]", 0, 1);
			
			#process the blank within name
			for ($i = 9; $i < @para; $i++)
			{
				 $name .= " $para[$i]";
			}
			if ($isdir eq 'd')
			{
				push @dir, "$pwd$name/";
			}
			else
			{
				# name & path & size & time
				my $secs = $ftp->mdtm("$pwd$name");
				my ($t0, $t1, $t2, $mday, $mon, $year, $t6, $t7, $t8) = localtime($secs);
				$mon+=1;
				$year+=1900;
				my $time = "$mday/$mon/$year";
					#or die "Cannot get file modtime: \$pwd: $pwd   \$name: $name \$!: $!";	
				#HERE ATTENTION!!! Line:3590 failed
				if (!$time)
				{
					$time = "NULL";
					say EXCEPTION "Cannot get file modtime: \$pwd: $pwd   \$name: $name \$!: $!";		
				}
				if (@output_cache < $CACHE_SIZE)
				{
					push @output_cache, "$name//$pwd/$size//$time\n";
					#$say ++$count, ': push @output_cache';
				}
				else
				{
					say ++$count, ': say OUT_FILE';
					print $out_file "@output_cache";
					@output_cache = ();
				}
				#say OUT_FILE1 "$name $pwd $size $time";
			}
		}
	}

	$ftp->quit()
		or die "Cannot quit";
}


sub init
{
	#
	#open files
	#
	for (my $i = 0; $i < @add; $i++)
	{
		#push @OUT_FILE, $add[$i];
		open $OUT_FILE[$i], ">$add[$i].index"
			or die "Cannot open file to write: $!";
	}
	open EXCEPTION, ">ftp_index_excetion"
		or die "Cannot open file to write: $!";
}









